<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="类别名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入类别名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="类别状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['category:subject:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="subjectList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="deptName" label="类别名称" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="orderNum" label="排序" align="center" width="60"></el-table-column>
      <el-table-column prop="type" label="类型" align="center" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_subject_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column prop="figure" label="键值" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button 
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['category:subject:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['category:subject:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['category:subject:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="75%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级类别">
              <treeselect
                v-model="form.parentId"
                :options="subjectOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级类别"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类型">
              <el-radio-group v-model="form.type">
                <el-radio
                  v-for="dict in dict.type.sys_subject_type"
                  :key="dict.value"
                  :label="dict.value"
                  @change="changeType(form.type)"
                 >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类别名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入类别名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          </el-row>
          <el-row>
          <el-col :span="12">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择停用则不能被访问" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                状态
              </span>
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if='isShow'>
            <el-form-item label="键值" prop="figure">
              <el-input v-model="form.figure" placeholder="请输入键值" style="width:37%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--步骤列表start-->
        <el-form ref="queryStep" :model="queryStep" label-width="100px" v-if='isShow' size="mini">
            <el-table v-loading="stepLoading" :data="stepList">
              <el-table-column label="步骤ID" align="center" prop="stepId" />
              <el-table-column label="识别码" align="center" prop="uuid" />
              <el-table-column label="步骤名称" align="center" prop="stepName" />
              <el-table-column label="小步骤名称" align="center" prop="minName" />
              <el-table-column label="大步骤结束提示" align="center" prop="message" />
              <el-table-column label="分值" align="center" prop="stepGrade" />
              <el-table-column label="步骤相同识别码" align="center" prop="sameNameStr" :show-overflow-tooltip="true" />
              <el-table-column label="子步骤识别码" align="center" prop="childNameStr"  :show-overflow-tooltip="true" />
              <el-table-column label="注意事项" align="center" prop="note" />
              <el-table-column label="简单难度" align="center" prop="simply">
                <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.sys_yes_no_st"
                    :value="scope.row.simply"
                  />
                </template>
              </el-table-column>
              <el-table-column label="普通难度" align="center" prop="ordinary" >
                <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.sys_yes_no_st"
                    :value="scope.row.ordinary"
                  />
                </template>
              </el-table-column>
              <el-table-column label="困难难度" align="center" prop="difficulte" >
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.sys_yes_no_st"
                  :value="scope.row.difficulte"
                />
              </template>
              </el-table-column>
              <el-table-column
                label="状态"
                align="center"
                prop="status"
              >
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.status"
                    active-value="0"
                    inactive-value="1"
                    @change="changeStatus(scope.row)"
                  ></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="排序" align="center" prop="sort" />
              <el-table-column label="更新时间" align="center" prop="updateTime" />
              <el-table-column
            label="操作"
            align="center"
            width="120"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-row>
                <el-button 
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="updateStep(scope.row)"
                  v-hasPermi="['task:step:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="deleteStep(scope.row)"
                  v-hasPermi="['task:step:remove']"
                >删除</el-button>
              </el-row>
            </template>
          </el-table-column>
          </el-table>
        </el-form>
        <!--步骤列表end-->
      <!-- 添加或修改步骤信息对话框 start-->
      <el-dialog :title="stepTitle" :visible.sync="stepOpen" width="600px" append-to-body>
        <el-form ref="stepForm" :model="stepForm" :rules="rules" label-width="80px">
          <el-form-item label="名称" prop="stepName">
            <el-input v-model="stepForm.stepName" placeholder="请输入步骤名称" />
          </el-form-item>
          <el-form-item label="小步骤名称" prop="minName">
            <el-input v-model="stepForm.minName" placeholder="请输入小步骤名称" />
          </el-form-item>
          <el-form-item label="识别码" prop="uuid">
            <el-input v-model="stepForm.uuid" placeholder="请输入识别码" />
          </el-form-item>
          
          <el-form-item label="同步骤识别码" prop="sameUuidGroup">
            <el-select
              style="width: 100%"
              v-model="stepForm.sameUuidGroup"
              multiple
              placeholder="请选择识别码(可多选)"
              clearable
            >
              <el-option
                v-for="item in allStep"
                :key="item.stepId"
                :label="item.stepName"
                :value="item.uuid"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="子识别码" prop="childUuidGroup">
            <el-select
              style="width: 100%"
              v-model="stepForm.childUuidGroup"
              multiple
              placeholder="请选择子识别码(可多选)"
              clearable
            >
              <el-option
                v-for="item in allStep"
                :key="item.stepId"
                :label="item.stepName"
                :value="item.uuid"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="结束提示" prop="message">
            <el-input
              v-model="stepForm.message"
              type="textarea"
              placeholder="请输入结束提示"
            />
          </el-form-item>
          <el-form-item label="成绩" prop="stepGrade">
            <el-input v-model="stepForm.stepGrade" placeholder="请输入成绩" />
          </el-form-item>
          <el-form-item label="注意事项" prop="note">
            <el-input
              v-model="stepForm.note"
              type="textarea"
              placeholder="请输入注意事项"
            />
          </el-form-item>
          <el-form-item label="标签" prop="tag">
            <el-input v-model="stepForm.tag" placeholder="请输入标签" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="简单难度" prop="simply">
                <el-radio-group v-model="stepForm.simply">
                  <el-radio
                    v-for="dict in dict.type.sys_yes_no_st"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="普通难度" prop="ordinary">
                <el-radio-group v-model="stepForm.ordinary">
                  <el-radio
                    v-for="dict in dict.type.sys_yes_no_st"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="困难难度" prop="difficulte">
            <el-radio-group v-model="stepForm.difficulte">
              <el-radio
                v-for="dict in dict.type.sys_yes_no_st"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="显示顺序" prop="sort">
            <el-input-number
              v-model="stepForm.sort"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitSetpForm">确 定</el-button>
            <el-button @click="cancelStep">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 添加或修改步骤信息对话框 end-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain icon="el-icon-plus" @click="addStep" v-hasPermi="['task:step:add']" v-if='isShow'>新增步骤</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubject, getSubject, delSubject, addSubject, updateSubject } from "@/api/category/subject";
import {listStep,getAll,getStep,delStep,addStep,updateStep,changeStatus} from "@/api/task/step";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Subject",
  dicts: ['sys_normal_disable','sys_subject_type','sys_yes_no_st'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 步骤遮罩层
      stepLoading: true,
      // 显示搜索条件
      showSearch: true,
      // 类别表格树数据
      subjectList: [],
      // 类别树选项
      subjectOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        visible: undefined
      },
      // 表单参数
      form: {},
      //步骤表单参数
      stepForm:{},
      //步骤查询参数
      queryStep: {},
      //步骤分页列表
      stepList: [],
      //步骤列表
      allStep:[],
      //步骤弹出层标题
      stepTitle:"",
      //是否显示步骤弹出层
      stepOpen: false,

      //故障现象ID
      deptId:0,
      //步骤内容的显示
      isShow: false,

      // 表单校验
      rules: {
        deptName: [
          { required: true, message: "类别名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "类别顺序不能为空", trigger: "blur" }
        ],
        uuid: [
          { required: true, message: "识别码不能为空", trigger: "blur" }
        ],
        stepName: [
          { required: true, message: "步骤名称不能为空", trigger: "blur" }
        ],
        minName: [
          { required: true, message: "小步骤名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    /** 查询类别列表 */
    getList() {
      this.loading = true;
      listSubject(this.queryParams).then(response => {
        this.subjectList = this.handleTree(response.data, "deptId");
        this.loading = false;
      });
    },
    /** 转换类别数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 查询类别下拉树结构 */
    getTreeselect() {
      listSubject().then(response => {
        this.subjectOptions = [];
        const subject = { deptId: 0, deptName: '主类别', children: [] };
        subject.children = this.handleTree(response.data, "deptId");
        this.subjectOptions.push(subject);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: 0,
        deptName: undefined,
        figure:undefined,
        orderNum: 0,
        type:"1",
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.isShow = false;
      this.stepList = [];
      this.reset();
      this.getTreeselect();
      if (row != null && row.deptId) {
        this.form.parentId = row.deptId;
        this.deptId = row.deptId;
      } else {
        this.form.parentId = 0;
      }
      //设置新增的时间戳与步骤关联
      let timestamp = parseInt(new Date().getTime()/1000);
      this.deptId = timestamp;
      this.stepLoading = false;
      this.open = true;
      this.title = "添加类别";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isShow = false;
      this.reset();
      this.getTreeselect();
      getSubject(row.deptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改类别";
        //故障现象ID
        this.queryStep.deptId = this.form.deptId;
        this.deptId = this.form.deptId;
        if(this.form.type == 6){
          this.isShow = true;
        }
        this.getStepList();
      });
      this.stepOpen = false;
    },

    //选择类型
    changeType() {
      if (this.form.type == 6){
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
            updateSubject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.deptId = this.deptId; //临时单位ID
            addSubject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？').then(function() {
        return delSubject(row.deptId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 获取步骤的分页列表 */
    getStepList() {
      this.stepLoading = true;
      //故障现象ID
      listStep(this.queryStep).then((response) => {
        this.stepList = response.rows;
        this.total = response.total;
        this.stepLoading = false;
      });
    },

    /** 获取步骤全部列表 */
    getAllStep() {
      getAll(this.queryStep).then((response) => {
        this.allStep = response.data;
      });
    },
    /** 新增步骤按钮操作 */
    addStep() {
      this.queryStep.deptId = undefined;
      this.resetSept();
      this.getAllStep();
      this.stepOpen = true;
      this.stepTitle = "添加步骤信息";
    },
    /** 修改步骤按钮操作 */
    updateStep(row) {
      this.queryStep.deptId = undefined;
      this.resetSept();
      this.getAllStep();
      const stepId = row.stepId;
      getStep(stepId).then((response) => {
        this.stepForm = response.data;
        this.stepOpen = true;
        this.stepTitle = "修改步骤信息";
      });
    },
    /** 删除步骤按钮操作 */
    deleteStep(row) {
      const stepIds = row.stepId;
      //故障现象ID，
      this.queryStep.deptId = this.deptId;
      this.$modal
        .confirm('是否确认删除步骤信息编号为"' + stepIds + '"的数据项？')
        .then(function () {
          return delStep(stepIds);
        })
        .then(() => {
          this.getStepList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 步骤表单重置
    resetSept() {
      this.stepOpen = false;
      this.stepForm = {
        deptId:undefined,
        stepName: undefined,
        minName: undefined,
        uuid: "",
        sameUuid: "",
        childUuid:"",
        message:"",
        stepGrade:"",
        note:"",
        tag:"",
        simply:"0",
        ordinary:"0",
        difficulte:"0",
        sort:0,
      };
      this.resetForm("stepForm");
    },

    //启用状态修改
    changeStatus(row) {
      let text = row.status === "0" ? "启用" : "禁用";
      this.$modal
        .confirm(
          "确认要" +
            text +
            '编号为“' +
            row.stepId +
            "，名称为" +
            row.stepName +
            '”的步骤吗？'
        )
        .then(function () {
          return changeStatus(row.stepId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },

    // 取消按钮
    cancelStep() {
      this.stepOpen = false;
      this.resetSept();
    },
    
    /** 提交按钮 */
    submitSetpForm() {
      this.$refs["stepForm"].validate((valid) => {
        if (valid) {
          if (this.stepForm.stepId != null) {
            updateStep(this.stepForm).then((response) => {
              this.$modal.msgSuccess("修改步骤成功");
              this.stepOpen = false;
              //故障现象ID，
              this.queryStep.deptId = this.deptId;
              this.getStepList();
            });
          } else {
            //赋值故障现象ID
            this.stepForm.deptId = this.deptId;
            //赋值新增的默认使用状态为未使用
            this.stepForm.useStatus = "2";
            addStep(this.stepForm).then((response) => {
              this.$modal.msgSuccess("新增步骤成功");
              this.stepOpen = false;
              //临时时间戳为故障现象ID
              this.queryStep.deptId = this.deptId;
              this.getStepList();
            });
          }
        }
      });
    },
  }
};
</script>
